package com.code2roc.fastboot.framework.extra.errorhandle;

import com.code2roc.fastboot.framework.datasource.DataSourceConfigException;
import com.code2roc.fastboot.framework.extra.enums.SystemErrorCodeEnum;
import com.code2roc.fastboot.framework.model.Result;
import com.code2roc.fastboot.framework.util.CommonUtil;
import com.code2roc.fastboot.framework.util.LogUtil;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@ControllerAdvice
@RestController
public class GlobalExceptionInterceptor {
    //Exception异常
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e){
        e.printStackTrace();
        LogUtil.writeLog("error","log", CommonUtil.getExceptionString(e));
        Result result = Result.errorResult();
        if (e.getClass().equals(HttpMediaTypeNotSupportedException.class)){
            result.setCode(SystemErrorCodeEnum.ErrorCode.RequestParamTypeError.get_value());
            result.setMsg(SystemErrorCodeEnum.ErrorCode.RequestParamTypeError.get_name());
        }else{
            result.setCode(SystemErrorCodeEnum.ErrorCode.SystemExecuteException.get_value());
            result.setMsg(SystemErrorCodeEnum.ErrorCode.SystemExecuteException.get_name());
        }

        return result;
    }

    //运行时异常
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Result exceptionHandler(RuntimeException e){
        e.printStackTrace();
        LogUtil.writeLog("error","log", CommonUtil.getExceptionString(e));
        Result result = Result.errorResult();
        if (e.getClass()== DataSourceConfigException.class){
            result.setCode(SystemErrorCodeEnum.ErrorCode.DataSourceNotExist.get_value());
            result.setMsg(SystemErrorCodeEnum.ErrorCode.DataSourceNotExist.get_name());
        }else{
            result.setCode(SystemErrorCodeEnum.ErrorCode.SystemRunningException.get_value());
            result.setMsg(SystemErrorCodeEnum.ErrorCode.SystemRunningException.get_name());
        }
        return result;
    }
}
